#include<iostream>
#include<string>
#include<cstdlib>
#include<sys/types.h>
#include<sys/wait.h>
#define len 1024
int main()
{
	int pipefd[2] = {0};
	int n = ::pipe(pipefd);
	if(n<0){
		std::cerr<<"pipe error"<<std::endl;
		::exit(1);
	}
	
	pid_t id = ::fork();
	if(id<0){
		std::cerr<<"fork error"<<std::endl;
		::exit(1);
	}
	else if(id == 0){
		::close(pipefd[0]);//子进程写，关闭读文件
		int cnt = 0;
		while(cnt<=10){
			std::string message = "child send to father : ";
			message+=std::to_string(cnt);
			::write(pipefd[1],message.c_str(),message.size());
			cnt++;
			::sleep(1);
		}

	}
	else{
		char buf[len] = {0};
		::close(pipefd[1]);//父进程读，关闭写文件
		while(true)
		{
			ssize_t num = read(pipefd[0],buf,len);
			if(num == 0)
				break;
			buf[num] = '\0';
			std::cout<<buf<<std::endl;
		}
		pid_t rid = waitpid(id,nullptr,0);//阻塞式等待子进程
		if(rid<0){
			std::cerr<<"waitpid error"<<std::endl;
			exit(1);
		}
		std::cout<<"wait sucess pid: "<<rid<<std::endl;
	}
	return 0;
}
